package com.foosun.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.foosun.dao.WxMessageDao;
import com.foosun.entity.message.Article;
import com.foosun.entity.message.res.NewsMessage;
import com.foosun.entity.message.res.TextMessage;
import com.foosun.entity.wechat.WxMessage;
import com.foosun.entity.wechat.WxUser;
import com.foosun.util.wechat.MessageUtil;
import com.foosun.util.wechat.RobotUtil;
import com.foosun.util.wechat.WxUserUtil;

/**
 * 核心服务类
 * 
 * @author leo
 * @date 2013-12-18
 */
@Service
public class WeixinService {
	
	@Autowired
	private WxAccessTokenService wxAccessTokenService;
	
	@Autowired
	private WxMessageDao wxMessageDao;
	
	private static WeixinService weixinService;
	
	@PostConstruct  
	public void init() {  
		weixinService = this;
		weixinService.wxAccessTokenService = this.wxAccessTokenService;
		weixinService.wxMessageDao = this.wxMessageDao;
	}	
	
	public static String processRequest(String secret) {
		String respMessage = null;
		
		try{
			String respContent = "请求处理异常，请稍候尝试！";
			
			// xml请求解析
			Map<String, String> requestMap = MessageUtil.parseXml(secret);

			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");
			//发送时间
			String creatTime = requestMap.get("CreateTime");
			
			// 文本消息
			if (MessageUtil.REQ_MESSAGE_TYPE_TEXT.equals(msgType.toLowerCase())) {
				respContent = "您发送的是文本消息！";
				
				// 文本消息内容  
			    String content = requestMap.get("Content");				
			    // 判断用户发送的是否是单个QQ表情  
			    if(RobotUtil.isQqFace(content)) {  
			        // 用户发什么QQ表情，就返回什么QQ表情  
			    	respMessage = content;  
			    }else{
			    	return articleHandler(fromUserName, toUserName, content,creatTime,requestMap);
			    }
			}else if(MessageUtil.REQ_MESSAGE_TYPE_LOCATION.equals(msgType.toLowerCase())){
				return "您发送的是坐标信息！";
			}	
			
			respMessage = generateTextMessage(fromUserName, toUserName, respContent);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return respMessage;
	}
	
	private static String articleHandler(String fromUserName, String toUserName, String content,String createTime,Map<String, String> requestMap){
        List<Article> articleList = new ArrayList<Article>();
        InforService inforService = InforService.getInforService();
        
        if ("1".equals(content)) {         	
            Article article = new Article();
            article = inforService.getById(1);
            articleList.add(article);  
        }
        // 多图文消息  
        else if ("2".equals(content)) {  
        	articleList = inforService.list("asc","2");
        }
        // 打卡功能、分享用户坐标
//        else if ("3".equals(content)) {
//        	return generateTextMessage(fromUserName, toUserName, "请分享您的地理位置给丰尚绿野！/:,@-D");
//        }
        // 显示帮助菜单
        else if ("?".equals(content) || "？".equals(content)) {
        	return generateTextMessage(fromUserName, toUserName, getMainMenu());
        }
        //存储消息141009
        else{
    		// 当收到的是非特殊会话消息时，存储该消息        	
        	if(articleList.size() == 0) {
        		WxMessage wm = new WxMessage();
        		wm.setFromuser(fromUserName);
        		wm.setTouser(toUserName);
        		wm.setCreatetime(Long.parseLong(createTime));
        		wm.setMsgtype(MessageUtil.REQ_MESSAGE_TYPE_TEXT);
        		wm.setContents(content);
        		weixinService.wxMessageDao.saveWxMess(wm);
        		return "";
        	}
        }
        
    	articleList = inforService.list("asc",content);
        return generateNewsMessage(fromUserName, toUserName, articleList);
	}
	
	private static String eventHandler(String fromUserName, String toUserName, Map<String, String> requestMap){
		String respMessage = new String();
		// 事件类型
		String eventType = requestMap.get("Event");
		// 订阅
		if (MessageUtil.EVENT_TYPE_SUBSCRIBE.equals(eventType)) {
			respMessage = generateTextMessage(fromUserName, toUserName, getMainMenu());
			saveUser(fromUserName,requestMap.get("CreateTime")); //FIXME H 14-6-26 本地库中添加关注者
		}
		// 取消订阅
		else if (MessageUtil.EVENT_TYPE_UNSUBSCRIBE.equals(eventType)) {
			// TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
			deleteUser(fromUserName); //FIXME H 14-6-26 本地库中删除关注者
		}
		// 自定义菜单点击事件
		else if (MessageUtil.EVENT_TYPE_CLICK.equals(eventType)) {
			String key = requestMap.get("EventKey");
			if(MessageUtil.KEY_ABOUT_MMYX.equals(key)){
		        List<Article> articleList = new ArrayList<Article>();
		        
	            Article article = new Article();  
	            article.setTitle("妈咪优选微信服务平台");  
	            // 图文消息中可以使用QQ表情、符号表情  
	            article.setDescription("妈咪优选微信服务平台");  
	            // 将图片置为空  
	            article.setPicUrl("http://42.96.176.134/statics/images/gogo_images/logo_w.png");  
	            article.setUrl("http://42.96.176.134");  
	            articleList.add(article); 
	            return generateNewsMessage(fromUserName, toUserName, articleList);
	            
			}else if(MessageUtil.KEY_GOOD.equals(key)){
				List<Article> articleList = new ArrayList<Article>();
				Article article = new Article();
	            article.setTitle("谢谢您的赞扬！\n");  
	            article.setDescription("我们会再接再励，顺便介绍您的好友扫一扫妈咪优选呗！");  
	            article.setPicUrl("http://42.96.176.134/statics/images/gogo_images/qr_code.jpg");  
	            article.setUrl("http://42.96.176.134");  		
	            articleList.add(article);
				respMessage = generateNewsMessage(fromUserName, toUserName, articleList);
				
			}else if(MessageUtil.KEY_CUSTOMER_SERVICE.equals(key)){
				respMessage = generateTextMessage(fromUserName, toUserName, "400-028-8888");
			}
		}
		// 自定义菜单查看事件
		else if (MessageUtil.EVENT_TYPE_VIEW.equals(eventType)) {
			
		}
		
		return respMessage;
	}
	
	private static String generateTextMessage(String fromUserName, String toUserName, String content){
		TextMessage textMessage = new TextMessage();
		textMessage.setToUserName(fromUserName);
		textMessage.setFromUserName(toUserName);
		textMessage.setCreateTime(new Date().getTime());
		textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
		textMessage.setFuncFlag(0);
		textMessage.setContent(content);
		String respMessage = MessageUtil.textMessageToXml(textMessage);
		return respMessage;
	}
	
	private static String generateNewsMessage(String fromUserName, String toUserName, List<Article> articleList){
		NewsMessage newsMessage = new NewsMessage();  
        newsMessage.setToUserName(fromUserName);  
        newsMessage.setFromUserName(toUserName);  
        newsMessage.setCreateTime(new Date().getTime());  
        newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);  
        newsMessage.setFuncFlag(0);
        // 设置图文消息个数  
        newsMessage.setArticleCount(articleList.size());  
        // 设置图文消息包含的图文集合  
        newsMessage.setArticles(articleList);  
        // 将图文消息对象转换成xml字符串  
        String respMessage = MessageUtil.newsMessageToXml(newsMessage);
		return respMessage;
	}
	
	/**
	 * robot的主菜单
	 * 
	 * @return
	 */
	public static String getMainMenu() {
		StringBuffer buffer = new StringBuffer();
		buffer.append("您好，我是丰尚绿野机器人，请回复数字选择服务：").append("\n\n");
		buffer.append("1  关于丰尚绿野").append("\n");
		buffer.append("2  联系丰尚绿野").append("\n");
		buffer.append("回复“?”显示此帮助菜单");
		return buffer.toString();
	}
	
	public static void main(String args[]){
		
		InforService iis = InforService.getInforService();
		Article article = iis.getById(1);
		/*long time = new Date().getTime();
		System.out.println(time);
		saveClock("owJNEuA0Aa3hqsZKdvxILu-_-l7M","","打卡",""+time);*/
		//saveMessage("owJNEuJKNx43vrYXfhhskSF_8bzA","yizhanggui","test","text",String.valueOf(time),new ArrayList());
		/*try {
			String openidlist = WxUserUtil.getFollowList("ZZN6nBCPyRdgyHO6KdxMiC9Ggf8XzAc9CyQidIqNyf5ZQUPVo9nRIKqLAqhlEtDxq2casRY4gEWz1JarBQSFtQ");
			System.out.println(openidlist);
			String t[] = MessageUtil.parseOpenidList(openidlist);
			//String[] t ={"owJNEuC1uqIXdIPC9BxsiUCvEObQ","owJNEuEgMZVmPXATnEN6wNxW0l78","owJNEuAfRAPvLYZFPB98KTy2ZdAk","owJNEuL4mC1pidQHtsb4imKnf75c","owJNEuIqILgHrKCoz8mn2WYHV4NQ","owJNEuJqa-UZMSMk0XKxvhAGjrPo","owJNEuMuzjw7gI8OcvuiASKfo1Cc","owJNEuH4iqTRMK3v589G8-8fFH18","owJNEuP9YuX0u-4epWTCOGEu--0E","owJNEuFkOzhhh3O9b0P_NvQrUbVY","owJNEuLaJ03ED6PDV81kU8dGkIPU","owJNEuLTVHUp4XnOngTDwb8DiFeI","owJNEuAqEhlMPgffSMn8NamE1XHo","owJNEuOeVlM8mAqbcMNxgtAqF3Og","owJNEuKNuZZSH83RLYLO7FoON8og","owJNEuKDhRzDnATNK_BGD2MPyvZ8","owJNEuAN-ODJ_C8RLUan1dqUONKM","owJNEuENUazbUTjG5EW7D1T4a1eY","owJNEuNog8vy8HP8WB9ef0NpFNMQ","owJNEuGLy289Rn4OLU-vEI9zOGFM","owJNEuK1S2ml8CgEHaZUoUGAC480","owJNEuJ8FejSH6aYHwlz0zQkp5dc","owJNEuA0Aa3hqsZKdvxILu-_-l7M","owJNEuPGL0bPxwIJjzDodLwk5iR8","owJNEuHeKmR0q5HB9zDvBXM9k-ls","owJNEuL-1uWwSv0roqlIKXS8bjJU","owJNEuBUgjRjxQzev1tDb531Xzes","owJNEuE69QW8adrpL8UfrHmKpSY4","owJNEuKIccyJ9GudufBz7emiYNvM","owJNEuIScyaaSFaSMeSvI4KCyyIk","owJNEuJKNx43vrYXfhhskSF_8bzA","owJNEuEnxyS1mRX57SU9gF0avMvU","owJNEuO6A4vWblZu9TuAz_6IOoyc","owJNEuMxSgiBDWR-Thb2LONrXY4E","owJNEuJnBG3e1DtKXhYVWamudeXg","owJNEuJLGB30NEvnl3sXHry5VYes","owJNEuKp7ILl8dGe8gMKZRmHcW_Y","owJNEuI1bAdgF8qkAJLjOST2GWvQ","owJNEuEb29FHUKGcXT3JUFO2tFm8","owJNEuN4ObNu1J-p6aWxJKlXRf9c","owJNEuLjkwcneYS267V_C4HHysX8","owJNEuM7HXrKEad2x4ykyVwkTDFM","owJNEuHi4kGM0R5q14zO8Bu9sEFE","owJNEuJsx8nEscRznj9e5gdG9m8M","owJNEuAzLDyL7dDIC8Wrsyj-72ZA","owJNEuGtA7OvAOjFIhzZURGwzxPE","owJNEuCbaKzyTmnDej4MRTBwWN5Q","owJNEuJkFG9vuzBOHnuYUdkU8q_4","owJNEuCFbyKXGNAITRWFw_CkeLR8","owJNEuDWMe3p0MlCj7_GuUas9y-E","owJNEuGVTbeQrlJDcDl73IufbGKM","owJNEuMbpgV6Ra5c_PPbOx7bf_q0","owJNEuD42PBmiXS159zjDkE4zH8M","owJNEuJ1yXqW2HxRwNSqZWc3mm6k","owJNEuNZz5VjunCb6MgITIShWn9Y","owJNEuL5sqLdUUUqrYhCEAE4mrPg","owJNEuK0U-quq1Y02um-_u7iWmNM","owJNEuLNFfLsB599l95Q0BCHh5S0","owJNEuILRFMrqilQRig5cBfYTGDs"};
			for(int i =0;i<t.length;i++){
				saveUser1(t[i],"ZZN6nBCPyRdgyHO6KdxMiC9Ggf8XzAc9CyQidIqNyf5ZQUPVo9nRIKqLAqhlEtDxq2casRY4gEWz1JarBQSFtQ");
				//deleteUser(t[i]);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}*/
		
		//sendOrder(1);
		
	}
	
	/**
	 * 保存关注者
	 * @param fromUserName
	 * @param creatTime
	 */
	public static void saveUser(String fromUserName,String creatTime){
		
		long time = 0;
		if(creatTime != null && !creatTime.equals(""))
			time = Long.parseLong(creatTime);
		int count = weixinService.wxMessageDao.getUserByOpenid(fromUserName, time);
		if(count == 0){
			WxUser wu = new WxUser();
			wu.setOpenid(fromUserName);
			wu.setSubscribe_time(time);
			try {
				String accessToken = weixinService.wxAccessTokenService.get("wx6eb63384bd102d9c");
				String userinfo = WxUserUtil.getUserInfo(accessToken, fromUserName);
				if(userinfo != null && !userinfo.equals("")){
					String gid = WxUserUtil.getUserGroup(accessToken, fromUserName);
					if(gid != null && !gid.equals("")){
						if(!gid.equals("1")){
							wu.setWxgroup_id(Integer.parseInt(gid));
							Map<String,String> map = MessageUtil.parseUserinfo(userinfo);
							wu.setNickname(map.get("nickname"));
							wu.setCountry(map.get("country"));
							wu.setProvince(map.get("province"));
							wu.setCity(map.get("city"));
							wu.setHeadimg(map.get("headimgurl"));
							String s = map.get("sex");
							if(s.equals("0"))wu.setSex("未设置");
							if(s.equals("1"))wu.setSex("男");
							if(s.equals("2"))wu.setSex("女");
						}else return;
					}				
				}
				weixinService.wxMessageDao.saveUser(wu);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 删除关注者
	 * @param fromUserName
	 */
	public static void deleteUser(String fromUserName){
		weixinService.wxMessageDao.deleteUser(fromUserName);		
	}

}
